/**
 * 单独处理spring-food.jpg图片
 */
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// 图片路径
const IMAGE_PATH = 'miniprogram/images/news/spring-food.jpg';
const OUTPUT_PATH = 'urgent_fixed_images/spring-food.jpg';

// 确保输出目录存在
const URGENT_OUTPUT_DIR = 'urgent_fixed_images';
if (!fs.existsSync(URGENT_OUTPUT_DIR)) {
  fs.mkdirSync(URGENT_OUTPUT_DIR);
}

async function fixImage() {
  try {
    console.log(`处理图片: ${IMAGE_PATH}`);
    
    // 检查文件是否存在
    if (!fs.existsSync(IMAGE_PATH)) {
      console.log(`文件不存在，尝试在云存储中创建替代图片...`);
      
      // 生成一个简单的替代图片，因为原始文件找不到
      const width = 800;
      const height = 600;
      
      const svgImage = `
      <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" fill="#f0f9eb"/>
        <text x="50%" y="50%" font-family="Arial" font-size="36" text-anchor="middle" fill="#44C289">春季健康饮食</text>
      </svg>
      `;
      
      const buffer = await sharp(Buffer.from(svgImage))
        .resize(width, height)
        .jpeg({ quality: 80 })
        .toBuffer();
      
      // 保存替代图片
      fs.writeFileSync(OUTPUT_PATH, buffer);
      console.log(`已创建替代图片: ${OUTPUT_PATH}`);
      
      // 创建目录结构（如果不存在）
      const dir = path.dirname(IMAGE_PATH);
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
        console.log(`创建目录: ${dir}`);
      }
      
      // 复制到原位置
      fs.copyFileSync(OUTPUT_PATH, IMAGE_PATH);
      console.log(`已复制替代图片到原始位置: ${IMAGE_PATH}`);
      
      const fileSize = fs.statSync(OUTPUT_PATH).size / 1024;
      console.log(`替代图片大小: ${fileSize.toFixed(2)}KB`);
      
      return;
    }
    
    // 正常处理图片
    const originalSize = fs.statSync(IMAGE_PATH).size / 1024;
    console.log(`原始大小: ${originalSize.toFixed(2)}KB`);
    
    // 加载图片
    const image = sharp(IMAGE_PATH);
    const metadata = await image.metadata();
    
    console.log(`原始尺寸: ${metadata.width}x${metadata.height}`);
    
    // 压缩参数
    const targetWidth = Math.floor(metadata.width * 0.5); // 缩小50%
    console.log(`目标尺寸: ${targetWidth}x${Math.floor(metadata.height * 0.5)}`);
    
    // 压缩图片
    const buffer = await image
      .resize(targetWidth)
      .jpeg({ quality: 70 })
      .toBuffer();
    
    const compressedSize = buffer.length / 1024;
    console.log(`压缩后大小: ${compressedSize.toFixed(2)}KB (减少 ${(originalSize - compressedSize).toFixed(2)}KB, ${((1 - compressedSize/originalSize) * 100).toFixed(2)}%)`);
    
    // 保存压缩后的图片
    fs.writeFileSync(OUTPUT_PATH, buffer);
    console.log(`保存到: ${OUTPUT_PATH}`);
    
    // 替换原始文件
    fs.writeFileSync(IMAGE_PATH, buffer);
    console.log(`替换原始文件: ${IMAGE_PATH}`);
    
  } catch (error) {
    console.error('处理图片时出错:', error);
  }
}

// 执行函数
fixImage().then(() => {
  console.log('处理完成');
}); 